package com.iwhalecloud.bss.kite.cucc.service.job.collectiongroup.singletask;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.customerOrderInformation.ICustomerOrderInfoService;
import com.iwhalecloud.bss.kite.cucc.client.api.customerOrderInformation.UserCenterClient;
import com.iwhalecloud.bss.kite.cucc.client.api.reception.ICustReceptionService;
import com.iwhalecloud.bss.kite.cucc.client.api.scene.ISceneCommitService;
import com.iwhalecloud.bss.kite.cucc.client.dto.batch.KiteBatchAcceptDetailDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.cust.CuccContextCustDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.customerOrderInformation.QryGrpMemberListByMemReq;
import com.iwhalecloud.bss.kite.cucc.client.dto.customerOrderInformation.QryGrpUserDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.ProdInstQryDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.UserQueryDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.scene.CuccCustInfoDetailDTO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.service.job.collectiongroup.KiteBatchAcceptDetailService;
import com.iwhalecloud.bss.kite.cucc.service.job.collectiongroup.StatusConst;
import com.iwhalecloud.bss.kite.dataservice.cache.DcSystemParamCache;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.ztesoft.bss.common.util.SpringUtil;
import com.ztesoft.zsmart.core.log.ZSmartLogger;

/**
 * @ClassName : AddMemberSingleTask
 * @Description : 加入成员
 * @Author : xie.zhengjun
 * @Date : 2021/5/11 16:01
 */
public class AddMemberSingleTask extends AbstractSingleTask {
    private final ZSmartLogger LOGGER = ZSmartLogger.getLogger(AddMemberSingleTask.class);

    public AddMemberSingleTask(KiteBatchAcceptDetailDTO kiteBatchAcceptDetail) {
        super(kiteBatchAcceptDetail);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = {})
    protected void handle() {
        String cartId = this.kiteBatchAcceptDetail.getCartId();
        String custId = DcSystemParamCache.getDcParamVal(LocalKeyConsts.COLLECTION_GROUP_CUST_ID);
        String checkMsg = "校验成功";
        String checkStatus = StatusConst.FAIL_STATUSCD;
        ICustomerOrderInfoService customerOrderInfoService = SpringUtil.getBean(ICustomerOrderInfoService.class);
        UserCenterClient userCenterClient = SpringUtil.getBean(UserCenterClient.class);
        IOperateSceneInstService operateSceneInstService = SpringUtil.getBean(IOperateSceneInstService.class);
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        KiteBatchAcceptDetailService kiteBatchAcceptDetailService = SpringUtil
            .getBean(KiteBatchAcceptDetailService.class);

        String sceneInstId = String.valueOf(this.kiteBatchAcceptDetail.getSceneInstId());
        String detailId = String.valueOf(this.kiteBatchAcceptDetail.getDetailId());


        String groupSerialNumber = "";
        String serialNumber = "";
        String telecomType = "";

        List<ProdInstQryDTO> userList;
        try {
            String attrJson = kiteBatchAcceptDetail.getAttrJson();
            if (KiteStringUtils.isEmpty(attrJson)) {
                checkMsg = "导入参数缺失，校验失败";
                return;
            }
            List<KiteAttr> kiteAttrs = JSONObject.parseArray(attrJson, KiteAttr.class);
            for (KiteAttr kiteAttr : kiteAttrs) {
                if (KiteStringUtils.isEqual(kiteAttr.getFieldName(), "groupSerialNumber")) {
                    groupSerialNumber = kiteAttr.getValue();
                }
                else if (KiteStringUtils.isEqual(kiteAttr.getFieldName(), "serialNumber")) {
                    serialNumber = kiteAttr.getValue();
                }
                else if (KiteStringUtils.isEqual(kiteAttr.getFieldName(), "telecomType")) {
                    telecomType = kiteAttr.getValue();
                }
            }
            //校验必填参数
            if (KiteStringUtils.isEmpty(groupSerialNumber)) {
                checkMsg = "收入归集集团业务号码为空!";
                return;
            }
            if (KiteStringUtils.isEmpty(serialNumber)) {
                checkMsg = "用户号码为空!";
                return;
            }
            if (KiteStringUtils.isEmpty(telecomType)) {
                checkMsg = "电信类型为空!";
                return;
            }
            // 这里是必要的：假如缓存失效了，调用这个方法会去查表，查到的话就还原场景（放入缓存）
            querySceneInstService.getSceneInst(sceneInstId, custId);
            LOGGER.info("正在校验detail_id>>>>>>>>>>>>>>----------------" + detailId);
            // 1、校验集团业务号码是否存在
            Map<String, String> map = new HashMap<>(5);
            map.put("userDiffCode", "28");
            map.put("isEffective", "1");
            map.put("accNum", groupSerialNumber);
            map.put("provinceCode", kiteBatchAcceptDetail.getProvinceId());
            UserQueryDTO userQueryDTO = customerOrderInfoService.queryUserList(map);
            userList = userQueryDTO.getUserList().getList();
            if (KiteObjectUtils.isEmpty(userList)) {
                checkMsg = "集团业务号码：" + groupSerialNumber + ",不存在集团用户信息，请检查";
                return;
            }
            /*String primaryProvinceCode = userList.get(0).getProvince_code();
            if (!KiteStringUtils.equals(primaryProvinceCode, kiteBatchAcceptDetail.getProvinceId())) {
                checkMsg = "收入归集集团成员加入不能跨省操作集团号码或成员号码";
                return;
            }*/
            // 2、校验成员业务号码是否存在
            List<Map<String, Object>> mapList = userCenterClient
                .qryGroupUserInfoDetails(sceneInstId, serialNumber, "", telecomType, "T");
            if (KiteListUtils.isEmpty(mapList)) {
                checkMsg = "成员业务号码：" + serialNumber + ",不存在用户信息，请检查";
                return;
            }

            // 3、校验是否已加入群组
            QryGrpMemberListByMemReq qryGrpMemberListByMemReq = new QryGrpMemberListByMemReq();
            qryGrpMemberListByMemReq.setMemSerialNumber(serialNumber);
            qryGrpMemberListByMemReq.setFinishState(LocalKeyConsts.GROUP_RELATION_FINISH_STATE_1);
            PageInfo<QryGrpUserDTO> qryGrpUserDTO = userCenterClient.qryGrpMemberListByMem(qryGrpMemberListByMemReq);
            if (qryGrpUserDTO.getTotal() > 0) {
                checkMsg = "成员业务号码：" + serialNumber + ",已加入归集集团，不允许再次加入";
                return;
            }
            LOGGER.info("校验成功--detail_id>>>>>>>>>>>>>>>----------------" + detailId);
            checkStatus = StatusConst.SUCCESS_STATUSCD;
            operateSceneInstService.putExtParameter(sceneInstId, "addGroupUserInfos", mapList);
        }
        catch (Exception e) {
//            e.printStackTrace();
            LOGGER.info("校验时出现异常--detail_id>>>>>>>>>>>>>>----------------" + detailId);
            checkMsg = "校验时出现异常：" + e.getMessage();
            return;
        }
        finally {
            kiteBatchAcceptDetailService
                .updateKiteBatchAcceptDetailCheckStatus(checkStatus, kiteBatchAcceptDetail.getDetailId(), checkMsg,
                    kiteBatchAcceptDetail.getBatchId());
        }
        // 4、校验通过进行转单操作
        commit(userList.get(0), sceneInstId, detailId, String.valueOf(kiteBatchAcceptDetail.getCreateStaff()),
            kiteBatchAcceptDetail.getCreateOrgId());
    }

    private void commit(ProdInstQryDTO groupUser, String sceneInstId, String detailId, String staffId, String orgId) {
        ICustReceptionService custReceptionService = SpringUtil.getBean(ICustReceptionService.class);
        ISceneCommitService sceneCommitService = SpringUtil.getBean(ISceneCommitService.class);
        KiteBatchAcceptDetailService kiteBatchAcceptDetailService = SpringUtil
            .getBean(KiteBatchAcceptDetailService.class);

        String dealResult = "";
        String statusCd = "";
        DataResult<String> result = new DataResult<>();
        try {
            CuccContextCustDTO contextCust = new CuccContextCustDTO();
            CuccCustInfoDetailDTO cuccCustInfoDTO = custReceptionService.getCustomerInfoNew(groupUser.getCust_id());
            if (Objects.nonNull(cuccCustInfoDTO)) {
                KiteBeanUtils.copyProperties(cuccCustInfoDTO, contextCust);
                contextCust.setProvinceCode(cuccCustInfoDTO.getProvinceCode());
                contextCust.setCustName(cuccCustInfoDTO.getCustName());
                contextCust.setLanId(cuccCustInfoDTO.getCityCode());
                contextCust.setRegionId(cuccCustInfoDTO.getBcityCode());
                contextCust.setCustType(cuccCustInfoDTO.getCustClassType());
                contextCust.setBbssCustId(cuccCustInfoDTO.getBbssCustId());
                contextCust.setCbssId(cuccCustInfoDTO.getCustId());
                contextCust.setAttrs(cuccCustInfoDTO.getAttrs());
            }
            dealCommonValue(sceneInstId, groupUser);
            result = sceneCommitService.commitScene(sceneInstId, staffId, orgId, contextCust, false, false);
        }
        catch (Exception e) {
//            e.printStackTrace();
            dealResult = "转单时出现异常：" + e.getMessage();
            statusCd = StatusConst.FAIL_STATUSCD;
            LOGGER.info("转单失败detailId>>>>>>>>>>>>>>----------------" + detailId);
        }
        finally {
            if (KiteStringUtils.isEqual(statusCd, StatusConst.FAIL_STATUSCD)) {
                kiteBatchAcceptDetailService
                    .updateKiteBatchAcceptDetailStatus(statusCd, kiteBatchAcceptDetail.getDetailId(), dealResult,
                        kiteBatchAcceptDetail.getBatchId());
            }
            else {
                if (KiteStringUtils.isEqual("0", result.getResultCode())) {
                    dealResult = "提交成功,订单编号：" + result.getResultObject();
                    statusCd = StatusConst.SUCCESS_STATUSCD;
                    LOGGER.info("转单成功detailId>>>>>>>>>>>>>>----------------" + detailId);
                }
                else {
                    dealResult = KiteStringUtils.isNotEmpty(result.getResultDetail()) ?
                        result.getResultDetail() :
                        "转单失败";
                    statusCd = StatusConst.FAIL_STATUSCD;
                    LOGGER.info("转单失败detailId>>>>>>>>>>>>>>----------------" + detailId);
                }
                kiteBatchAcceptDetailService
                    .updateKiteBatchAcceptDetailStatus(statusCd, kiteBatchAcceptDetail.getDetailId(), dealResult,
                        kiteBatchAcceptDetail.getBatchId());
            }
        }
    }

    /**
     * 处理转单公共属性逻辑
     *
     * @param sceneInstId
     * @param groupUser
     */
    private void dealCommonValue(String sceneInstId, ProdInstQryDTO groupUser) {
        IOperateSceneInstService operateSceneInstService = SpringUtil.getBean(IOperateSceneInstService.class);

        operateSceneInstService.putExtParameter(sceneInstId, "business_number", groupUser.getSerial_number());
        operateSceneInstService.setCommonAttrValue(sceneInstId, "business_number", groupUser.getSerial_number(),
            groupUser.getSerial_number());

        operateSceneInstService
            .setCommonAttrValue(sceneInstId, "PRIMARY_USER_ID", groupUser.getUser_id(), groupUser.getUser_id());
        operateSceneInstService
            .setCommonAttrValue(sceneInstId, "group_user_name", groupUser.getUser_name(), groupUser.getUser_name());

    }

}
